import datetime

from flask import session
from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey, Float, func, Boolean
from sqlalchemy.orm import relationship

from db_linker import db

Base = db.Model


class Movies(Base):
    """电影"""

    __tablename__ = 'movies'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    directors = Column(String(255))  # 导演
    actors = Column(Text)  # 演员
    desc = Column(Text, default='')  # 描述
    year = Column(Text)  # 年份
    image_path = Column(String(255))  # 海报

    created_at = Column(DateTime, default=datetime.datetime.now)
    updated_at = Column(DateTime, default=datetime.datetime.now)

    movie_genre_link = relationship('MovieGenreLink', lazy='dynamic')  # 多对多 关联关系

    def get_genres(self):
        return [
            link.genre
            for link in self.movie_genre_link
        ]

    def has_genres(self, genre_id):
        li_movie_genres_id = [
            link.genre.id
            for link in self.movie_genre_link
        ]

        return int(genre_id) in li_movie_genres_id

    def get_score_count(self):
        return UserScoreOfMovie.query.filter(
            UserScoreOfMovie.movie_id == self.id
        ).count()

    def get_avg_score(self):
        # 当前电影-平均评分
        sum_val = db.session.query(
            func.sum(UserScoreOfMovie.score)
        ).filter(
            UserScoreOfMovie.movie_id == self.id
        ).scalar() or 0

        if not sum_val: return 0

        count = self.get_score_count()

        return round(sum_val / count, 2)

    def get_comments_count(self):
        """获取 电影-评论数量"""
        return UserCommentsOfMovie.query.filter(
            UserCommentsOfMovie.movie_id == self.id
        ).count()

    def get_user_favor_movie_status(self):
        """获取 当前用户-当前电影-喜欢状态"""

        if 'user' not in session:
            return None

        now_favor = UserFavorOfMovie.query.filter(
            UserFavorOfMovie.user_id == session['user']['id'],
            UserFavorOfMovie.movie_id == self.id
        ).first()

        return not not now_favor

    # def my_score(self):
    #     """当前用户-评分"""
    #
    #     if 'user' in session:
    #         pass
    #     pass


class MovieGenreLink(Base):
    __tablename__ = 'movie_genre_link'

    id = Column(Integer, primary_key=True)
    movie_id = Column(ForeignKey('movies.id'))
    genre_id = Column(ForeignKey('genres.id'))

    genre = relationship('Genres')  # 关联对象


class Genres(Base):
    """类型"""

    __tablename__ = 'genres'

    id = Column(Integer, primary_key=True)
    value = Column(String(255))

    def genre_base_info_(self):
        return {
            'id': self.id,
            'value': self.value,
        }


class User(Base):
    """用户"""

    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    username = Column(String(255))
    password = Column(String(255))
    avatar_path = Column(String(255))

    age = Column(Integer)
    created_at = Column(DateTime, default=datetime.datetime.now)
    updated_at = Column(DateTime, default=datetime.datetime.now)

    def user_base_info(self):
        return {
            'id': self.id,
            'username': self.username,
            'age': self.age,
            'avatar_path': self.avatar_path,
        }


class UserGenreLink(Base):
    """用户-偏好的类型"""

    __tablename__ = 'user_genre_link'

    id = Column(Integer, primary_key=True)
    user_id = Column(ForeignKey('user.id'))
    genre_id = Column(ForeignKey('genres.id'))


class UserScoreOfMovie(Base):
    """用户-电影-评分"""

    __tablename__ = 'user_score_of_movie'

    id = Column(Integer, primary_key=True)
    user_id = Column(ForeignKey('user.id'))
    movie_id = Column(ForeignKey('movies.id'))
    score = Column(Float)
    created_at = Column(DateTime, default=datetime.datetime.now)
    updated_at = Column(DateTime, default=datetime.datetime.now)


class UserCommentsOfMovie(Base):
    """电影-用户-评论"""
    __tablename__ = 'user_comments_of_movie'

    id = Column(Integer, primary_key=True)
    user_id = Column(ForeignKey('user.id'))
    movie_id = Column(ForeignKey('movies.id'))

    content = Column(Text)
    created_at = Column(DateTime, default=datetime.datetime.now)
    updated_at = Column(DateTime, default=datetime.datetime.now)

    agree = Column(Integer, default=0)
    disagree = Column(Integer, default=0)

    user = relationship('User')
    movie = relationship('Movies')

    def comment_base_info(self):
        """评论基本信息"""
        return {
            'id': self.id,
            'content': self.content,
            'created_at': str(self.created_at),
            'user': self.user.user_base_info(),
            'agree': self.agree,
            'disagree': self.disagree
        }


class CommentAgree(Base):
    """评论 赞与踩 用户记录表"""

    __tablename__ = 'comment_agree'

    id = Column(Integer, primary_key=True)
    comment_id = Column(ForeignKey('user_comments_of_movie.id'))
    user_id = Column(ForeignKey('user.id'))
    agree = Column(Boolean)  # true 为赞，false 为踩
    created_at = Column(DateTime, default=datetime.datetime.now)


class UserFavorOfMovie(Base):
    """用户-喜欢的电影"""

    __tablename__ = 'user_favor_of_movie'

    id = Column(Integer, primary_key=True)
    user_id = Column(ForeignKey('user.id'))
    movie_id = Column(ForeignKey('movies.id'))
    created_at = Column(DateTime, default=datetime.datetime.now)
